import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:openim_common/openim_common.dart';

class ChatVideoView extends StatefulWidget {
  const ChatVideoView({
    Key? key,
    required this.message,
    required this.isISend,
    this.sendProgressStream, // 添加进度流参数
    this.isMultiSelectMode = false,
    this.onToggleSelection,
  }) : super(key: key);
  
  final bool isISend;
  final Message message;
  final Stream<MsgStreamEv<int>>? sendProgressStream; // 添加进度流参数
  final bool isMultiSelectMode;
  final Function(Message message)? onToggleSelection;

  @override
  State<ChatVideoView> createState() => _ChatVideoViewState();
}

class _ChatVideoViewState extends State<ChatVideoView> {
  String? _videoPath;
  String? _videoUrl;
  String? _snapshotUrl;
  late double _trulyWidth;
  late double _trulyHeight;
  int _uploadProgress = 0; // 添加上传进度变量
  StreamSubscription? _progressSubscription; // 添加进度订阅

  Message get _message => widget.message;
  Widget? _child;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
    _listenToProgress(); // 监听进度
  }
  void _listenToProgress() {
    _progressSubscription = widget.sendProgressStream?.listen((event) {
      if (event.id == _message.clientMsgID) {
        setState(() {
          _uploadProgress = event.value;
        });
      }
    });
  }
  @override
  void dispose() {
    _progressSubscription?.cancel(); // 取消订阅
    super.dispose();
  }
  void _initializeVideo() {
    final video = _message.videoElem;
    _videoPath = video?.videoPath;
    _videoUrl = video?.videoUrl;
    
    debugPrint('初始化视频消息: URL=$_videoUrl, Path=$_videoPath');
    
    // 获取缩略图URL
    final snap = video?.snapshotUrl;
    if (snap != null && snap.isNotEmpty) {
      _snapshotUrl = snap.adjustThumbnailAbsoluteString(960);
      debugPrint('视频缩略图URL: $_snapshotUrl');
    }

    // 计算显示尺寸
    var w = video?.snapshotWidth?.toDouble() ?? 200.0;
    var h = video?.snapshotHeight?.toDouble() ?? 150.0;

    // 确保最小尺寸
    if (w < 100) w = 200.0;
    if (h < 100) h = 150.0;

    // 计算显示尺寸，参考图片消息的逻辑
    if (pictureWidth > w) {
      _trulyWidth = w;
      _trulyHeight = h;
    } else {
      _trulyWidth = pictureWidth;
      _trulyHeight = _trulyWidth * h / w;
    }

    final height = pictureWidth * 1.sh / 1.sw;

    if (_trulyHeight > 2 * height) {
      _trulyHeight = _trulyWidth;
    }

    debugPrint('视频显示尺寸: ${_trulyWidth}x${_trulyHeight}');

    // 立即初始化_child，避免null值
    _child = _buildVideoPlaceholder();
    
    // 异步创建实际的子视图
    _createChildView();
  }

  Future<bool> _checkingPath() async {
    var valid = IMUtils.isNotNullEmptyStr(_videoPath);
    if (!valid) {
      return false;
    }
    if (Platform.isIOS) {
      final exist = await File(_videoPath!).exists();
      valid = valid && exist;
    } else {
      valid = valid && File(_videoPath!).existsSync();
    }
    _message.exMap['validPath_$_videoPath'] = valid;

    return valid;
  }

  bool? get isValidPath => _message.exMap['validPath_$_videoPath'];

  void _createChildView() {
    Widget childWidget;
    
    // 优先显示网络缩略图
    if (IMUtils.isNotNullEmptyStr(_snapshotUrl)) {
      debugPrint('使用网络缩略图: $_snapshotUrl');
      childWidget = _buildVideoThumbnail(url: _snapshotUrl!);
      _child = childWidget;
      if (mounted) {
        setState(() {});
      }
    } 
    // 如果是发送方且有本地路径，检查本地文件
    else if (widget.isISend && IMUtils.isNotNullEmptyStr(_videoPath)) {
      debugPrint('检查本地视频文件: $_videoPath');
      _checkingPath().then((isValid) {
        if (isValid) {
          debugPrint('本地视频文件存在，使用本地缩略图');
          if (mounted) {
            setState(() {
              _child = _buildLocalVideoThumbnail(path: _videoPath!);
            });
          }
        } else {
          debugPrint('本地视频文件不存在，使用占位符');
          if (mounted) {
            setState(() {
              _child = _buildVideoPlaceholder();
            });
          }
        }
      });
    } 
    // 默认情况已经在初始化时设置了占位符
    else {
      debugPrint('使用默认占位符');
      // _child 已经在初始化时设置为占位符，无需再次设置
    }
  }
  
  Widget _buildVideoThumbnail({required String url}) {
    debugPrint('ChatVideoView: 构建网络缩略图，URL: $url');
    return Stack(
      alignment: Alignment.center,
      children: [
        ImageUtil.networkImage(
          url: url,
          width: _trulyWidth,
          height: _trulyHeight,
          fit: BoxFit.cover,
          errorWidget: _buildVideoPlaceholder(),
        ),
        // 播放按钮
        Container(
          width: 50.w,
          height: 50.w,
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.5),
            shape: BoxShape.circle,
          ),
          child: Icon(
            Icons.play_arrow,
            color: Colors.white,
            size: 30.w,
          ),
        ),
        // 视频时长显示
        if (_message.videoElem?.duration != null)
          Positioned(
            bottom: 8.w,
            right: 8.w,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.w),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.7),
                borderRadius: BorderRadius.circular(4.w),
              ),
              child: Text(
                _formatDuration(_message.videoElem!.duration!),
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12.sp,
                ),
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildLocalVideoThumbnail({required String path}) => Stack(
        children: [
          Container(
            width: _trulyWidth,
            height: _trulyHeight,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: borderRadius(widget.isISend),
            ),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.videocam,
                    size: 40.w,
                    color: Colors.grey[600],
                  ),
                  8.verticalSpace,
                  Text(
                    '本地视频',
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 12.sp,
                    ),
                  ),
                ],
              ),
            ),
          ),
          // 播放按钮覆盖层
          Positioned.fill(
            child: Container(
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.1),
                borderRadius: borderRadius(widget.isISend),
              ),
              child: Center(
                child: Container(
                  width: 50.w,
                  height: 50.w,
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.9),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.play_arrow,
                    size: 30.w,
                    color: Colors.black87,
                  ),
                ),
              ),
            ),
          ),
          // 视频时长显示
          if (_message.videoElem?.duration != null)
            Positioned(
              bottom: 8.h,
              right: 8.w,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.7),
                  borderRadius: BorderRadius.circular(4.r),
                ),
                child: Text(
                  _formatDuration(_message.videoElem!.duration!),
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 10.sp,
                  ),
                ),
              ),
            ),
        ],
      );

  Widget _buildVideoPlaceholder() => Container(
        width: _trulyWidth,
        height: _trulyHeight,
        decoration: BoxDecoration(
          color: Colors.grey[300],
          borderRadius: borderRadius(widget.isISend),
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.videocam_off,
                size: 40.w,
                color: Colors.grey[600],
              ),
              8.verticalSpace,
              Text(
                '视频',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 12.sp,
                ),
              ),
              if (_message.videoElem?.duration != null) ...[
                4.verticalSpace,
                Text(
                  _formatDuration(_message.videoElem!.duration!),
                  style: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 10.sp,
                  ),
                ),
              ],
            ],
          ),
        ),
      );

  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    final child = ClipRRect(
      borderRadius: borderRadius(widget.isISend),
      child: GestureDetector(
        onTap: () {
          // 在多选模式下，优先处理选中逻辑
          if (widget.isMultiSelectMode) {
            widget.onToggleSelection?.call(_message);
            return;
          }
          
          // 点击播放视频
          debugPrint('点击播放视频: $_videoUrl, $_videoPath');
          if (_videoUrl != null || _videoPath != null) {
            try {
              IMUtils.previewMediaFile(
                context: context,
                message: _message,
              );
            } catch (e) {
              debugPrint('预览视频失败: $e');
              IMViews.showToast('视频播放失败');
            }
          }
        },
        child: SizedBox(
          width: _trulyWidth, 
          height: _trulyHeight, 
          child: _child ?? _buildVideoPlaceholder(),
        ),
      ),
    );
    return child;
  }
}